﻿using Basic.FlowApplication.Model.AuditLog;
using Basic.FlowModel;
using Basic.FlowRemoteModel;

namespace Basic.FlowApplication.Linq
{
    internal static class AuditFilterLinq
    {
        public static List<AfootAuditLogItem> Filters ( this List<AfootAuditLogItem> items, AfootAuditLogItem log )
        {
            List<AfootAuditLogItem> list;
            if ( ConstDic.MarkeStatus.Contains(log.MarkState) )
            {
                AfootAuditLogItem state = _GetState(log.OptItemId.Value, items);
                state.Status = log.Status;
                list = items.FindAll(a => a.BatchNo == state.BatchNo && ConstDic.MuliteFilterStatus.Contains(a.Status) == false);
            }
            else
            {
                list = items.FindAll(a => a.BatchNo == log.BatchNo && ConstDic.MuliteFilterStatus.Contains(a.Status) == false);
            }
            list.ForEach(c =>
            {
                if ( ConstDic.ReturnStatus.Contains(c.Status) )
                {
                    c.Status = _GetEndStatus(c, items);
                }
            });
            return list;
        }

        private static FlowAuditItemStatus _GetEndStatus ( AfootAuditLogItem dto, List<AfootAuditLogItem> items )
        {
            if ( dto.Status == FlowAuditItemStatus.已委托 )
            {
                AfootAuditLogItem item = items.Find(a => a.OptItemId == dto.Id && a.MarkState == FlowItemMarkState.回源);
                if ( item != null )
                {
                    return item.Status;
                }
            }
            AfootAuditLogItem t = items.Find(a => a.OptItemId == dto.Id);
            if ( ConstDic.ReturnStatus.Contains(t.Status) )
            {
                return _GetEndStatus(t, items);
            }
            return t.Status;
        }
        private static AfootAuditLogItem _GetState ( long itemId, List<AfootAuditLogItem> items )
        {
            AfootAuditLogItem item = items.Find(a => a.Id == itemId);
            if ( item.MarkState == FlowItemMarkState.回源 )
            {
                return _GetState(item.OptItemId.Value, items);
            }
            if ( ConstDic.MarkeStatus.Contains(item.MarkState) )
            {
                return _GetState(item.OptItemId.Value, items);
            }
            return item;
        }
    }
}
